var ctx=window.daijia.ctx;
var offset=0;
var limit=20;
var pagingLimit=20;//显示分页时的条数
var currentTotalElements=0;//当前显示总条数
var pageLoading=true;//是否能滚动加载
var hasShowPages=false;//是否已显示分页
var firstLoadPages=true;//分页初始化时 不自动加载
//筛选条件,
var search_params=null;
var search_startTime=null;
var search_endTime=null;

$(document).ready(function(){

	$("#startTime").datetimepicker({
		format: "yyyy-mm-dd HH:ii",
		language: 'zh-CN',
		showMeridian: true,
		autoclose: true,
		todayBtn: true
	});
	$("#endTime").datetimepicker({
		format: "yyyy-mm-dd HH:ii",
		language: 'zh-CN',
		showMeridian: true,
		autoclose: true,
		todayBtn: true
	});

	var newDate = new Date();
	var startDate = new Date();
	startDate.setDate(startDate.getDate()-30);
	var startTimeStr=startDate.getFullYear()+"-"+((startDate.getMonth()+1)>9?(startDate.getMonth()+1):'0' + (startDate.getMonth()+1))+"-"+(startDate.getDate()>9?startDate.getDate():'0' + startDate.getDate())+" "+"00:00";
	var endTimeStr=newDate.getFullYear()+"-"+((newDate.getMonth()+1)>9?(newDate.getMonth()+1):'0' + (newDate.getMonth()+1))+"-"+(newDate.getDate()>9?newDate.getDate():'0' + newDate.getDate())+" "+"23:59";
	$("#startTime").val(startTimeStr);
	$("#endTime").val(endTimeStr);
	search_startTime=$("#startTime").val();
	search_endTime=$("#endTime").val();
	console.log(1111,search_endTime)
    initdata(false);


});

$("#startTime").datetimepicker({format: 'yyyy-mm-dd HH:ii', language: 'zh-CN', minView: 'hour', pickDate: true, pickTime: false, inputMask: false, autoclose: true });
$("#endTime").datetimepicker({format: 'yyyy-mm-dd HH:ii', language: 'zh-CN', minView: 'hour', pickDate: true, pickTime: false, inputMask: false, autoclose: true });

	initdata(false);

	window.setInterval(function(){
		initdata(false);
	},1000*60);
	//备注
	$(document).on("click",'.modifyCash',function(){
			var  orderId=$(this).attr('orderId');
			var orderNo=$(this).attr('orderNo');
			var orderMemo=$(this).attr('orderMemo');
			$('#orderId').val(orderId);
			$('#orderNo').html(orderNo);
			$('#oldmemo').val(orderMemo);
	    	$('#dialog_modifyCash').modal();
	});
	//确认加油
	$(document).on("click",'.confirmRefuel',function(){
		if(window.confirm('确认加油吗？')){
			$.get(ctx+'/gaslogin/updateStauts',{'orderId':$(this).attr('orderId'),'status':1},function(data){
		           if(data.success){
		                $.scojs_message("操作成功", $.scojs_message.TYPE_OK);
		                setTimeout(function(){
							window.location.reload(true);
						}, 1000);
			       }else{
		                $.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
		                setTimeout(function(){
							window.location.reload(true);
						}, 1000);
			       }
			    },'json');
		}

	});
	//查看订单
	$(document).on("click",'.selectDetail',function(){
			$.get(ctx+'/gaslogin/queryById',{'orderId':$(this).attr('orderId')},function(data){
		           if(data.code==0){
		        	   var order = data.data;
		        	   $("#orderNum").html(order.orderNum);
		        	   $("#passengerName").html(order.passengerName);
		        	   $("#passengerPhone").html(order.passengerPhone);
		        	   $("#gasNum").html(order.gasNum);
		        	   $("#compressorGun").html(order.compressorGun);
		        	   $("#createOrder").html((new Date(order.created).Format("yyyy-MM-dd")));
		        	   $("#money").html(order.money+"元");
		        	   $("#realMoney").html(order.realMoney+"元");
		        	   $("#gsName").html(order.gsName);
		        	   $("#gsServiceNo").html(order.gsServiceNo);
		        	   $("#discountMoney").html(order.discountMoney+"元");
		        	   if(order.payType=="alipay"){
	            			$("#payType").html("支付宝");
	            		}else if(order.payType=="weixin"){
	            			$("#payType").html("微信");
	            		}else if(order.payType=="balance"){
	            			$("#payType").html("余额");
	            		}else if(order.payType=="unionpay"){
	            			$("#payType").html("银联");
	            		}
		        	   if(order.status==0){
		        		   $("#status").html("待处理");
		        	   }else if(order.status==1){
		        		   $("#status").html("已完成");
		        	   }
		        	   $("#memoOrder").text(order.memo==null?"":order.memo);
		        	   $('#dialog_order').modal();
			       }else{
		                $.scojs_message("请稍后再试", $.scojs_message.TYPE_ERROR);
			       }
			    },'json');

	});

    $("#save").click(function(){

    	if ($('#memo').val()=="") {
			$.scojs_message("请填写备注信息", $.scojs_message.TYPE_ERROR);
			return false;
		}

     	$('#dialog_modifyCash').modal("hide");
		$.post(ctx+'/gaslogin/remark',{'id':$('#orderId').val(),'memo':$('#memo').val()},function(data){
           if(data.success){
                $.scojs_message("备注成功", $.scojs_message.TYPE_OK);
                setTimeout(function(){
					window.location.reload(true);
				}, 1000);
	       }else{
                $.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
                setTimeout(function(){
					window.location.reload(true);
				}, 1000);
	       }
	    },'json');
    });
    $("#close_modal_memo").click(function(){
    	$('#dialog_modifyCash').modal("hide");
    });

    //导出
    $("#export_button").click(function(){
		window.location=ctx+"/gasstation/exportOrder?"+
		                "statusSelect="+$("#statusSelect").val()+"&params="+$("#params").val()+
		                "&startTime="+$("#startTime").val()+"&endTime="+$("#endTime").val();
	});

	//查询
	$("#searchButton").click(function(){
		search_params=$("#params").val();
		search_startTime=$("#startTime").val();
		search_endTime=$("#endTime").val();

		if($("#startTime").val()!="" && $("#endTime").val()!=""){
			if($("#startTime").val()>$("#endTime").val()){
				 $.scojs_message("启始日期不能大于结束日期", $.scojs_message.TYPE_ERROR);
				 return false;
			}
		}



		offset=0;
		initdata(false);
	});

	$(document).on("keydown","body",function(){
		if(window.event.keyCode == 13){
			$("#searchButton").click();
		}
	});

	//开始导出


function initdata(isappend){
    console.log(1111,search_endTime)
	$.ajax({
        url : ctx+'/gasstation/orderListData',
        type:'GET',
        async:false,
        dataType : 'json',
        data : {
        	"statusSelect":$("#statusSelect").val(),
        	"params":search_params,
        	"startTime":search_startTime,
        	"endTime":search_endTime,
        	"pager.offset":offset,
        	"limit":limit,
        },
        success : function(result){
        	console.debug(result);
        	var newcontent = '';
        	var totalElements=result.totalElements;
        	$("#NoData").text("");

        	if(totalElements>0){
        		$(result.content).each(function(index,data){
        			var memoButton="";
        			var selectButton="";
        			var stauts="";

            		memoButton="<a href='#' orderId='"+data.id+"' orderNo='"+data.orderNum+"' orderMemo='"+(data.memo==null?"":data.memo)+"' class='btn-link modifyCash'>添加备注</a>";
            		confirmButton="<a href='#' orderId='"+data.id+"'  class='btn-link confirmRefuel'>确认加油</a>";
            		selectButton="<a href='#' orderId='"+data.id+"'  class='btn-link selectDetail'>查看详情</a>";

            		var allButton="";
            		var status="";
            		if(data.status==0){
            			status="待处理";
            			allButton=confirmButton+"&nbsp;&nbsp;"+memoButton;
            		}else if(data.status==1){
            			status="已完成";
            			allButton=selectButton+"&nbsp;&nbsp;"+memoButton;
            		}


            		var memotr=data.memo;
            		if(null!=memotr && memotr.length>10){
            			memotr=memotr.substring(0,10)+"...";
            		}else if(null==memotr){
            			memotr="";
            		}
            		var payTypeStr="";
            		if(data.payType=="alipay"){
            			payTypeStr="支付宝";
            		}else if(data.payType=="weixin"){
            			payTypeStr="微信";
            		}else if(data.payType=="balance"){
            			payTypeStr="余额";
            		}else if(data.payType=="unionpay"){
            			payTypeStr="银联";
            		}
            		var companyNames="";
            		if(main){
            			companyNames="<td>"+(data.companyName==null?"":data.companyName)+"</td>";
            		}



	    newcontent+="<tr class='grid-data tr-hui'  >"+
						"<td>"+allButton+"</td>"+
						"<td>"+status+"</td>"+
						"<td>"+data.gsServiceNo+"</td>"+
						"<td>"+data.gsName+"</td>"+
						companyNames+
						"<td>"+data.passengerName+"</td>"+
						"<td>"+data.passengerPhone+"</td>"+
						"<td><a class='selectDetail btn-link' orderId='"+data.id+"'>"+data.orderNum+"</a></td>"+
						"<td>"+data.gasNum+"</td>"+
						"<td>"+data.compressorGun+"</td>"+
						"<td>"+(data.money != null ? data.money.toFixed(2) : 0)+"元</td>"+
						"<td>"+(data.realMoney != null ? data.realMoney.toFixed(2) : 0)+"元</td>"+
						"<td>"+(data.discountMoney != null ? data.discountMoney.toFixed(2) : 0)+"元</td>"+
						"<td>"+data.created+"</td>"+
						"<td>"+payTypeStr+"</td>"+
						"<td>"+memotr+"</td>"+
					"</tr>";
        		});
        	}
        	else{
              	 $("#NoData").text("当前页面暂无记录 ");
              	}

        	if(!isappend){
        		$("#order_tbody .grid-data").remove();
        	}
        	$("#order_tbody").append(newcontent);
        	$("#order_tbody .grid-data").each(function(index,element){
        		$(element).fadeIn(200+(index*35));
        	});
        	if(!hasShowPages){
        		if(!isappend){
            		currentTotalElements=result.content.length;
            		pageLoading=true;
            	}else{
            		if(currentTotalElements<totalElements){
            			currentTotalElements+=result.content.length;
            			pageLoading=true;
            		}else{
            			pageLoading=false;
            		}
            	}
        	}
        	if(hasShowPages){
    			firstLoadPages=true;
        		$(".pageshow li a").html("共"+totalElements+" 条数据");
        		$(".pagedata").paging(totalElements, {
        			format: '[< ncnnn >]',
        			perpage: pagingLimit,
        			page:(offset/limit)+1,
        			onSelect: function (page) {
        				limit=pagingLimit;
        				offset=(page-1)*limit;
        				if(!firstLoadPages){
        					initdata(false);
        				}
        				firstLoadPages=false;
        		    	return false;
        			},
        			onFormat: function (type) {
        				switch (type) {
        				case 'block': // n and c
        					if (!this.active)
        						return '';
        					else if (this.value != this.page)
        						return '<li><a href="#">' + this.value + '</a></li>';
        					return '<li class="active"><a href="#">' + this.value + '</a></li>';
        				case 'next': // >
        					return '<li><a href="#">&rsaquo;</a><li>';
        				case 'prev': // <
        						return '<li><a href="#">&lsaquo;</a><li>';
        				case 'first': // [
        						return '<li><a href="#">&laquo;</a><li>';
        				case 'last': // ]
        						return '<li><a href="#">&raquo;</a></li>';
        				}
        			}
        		});
        	}else{
            		pageLoading=false;
            		hasShowPages=true;
            		$(".pageshow").show();
            		$(".pagedata").show();
            		$(".pageshow li a").html("共"+totalElements+" 条数据");
            		$(".pagedata").paging(totalElements, {
            			format: '[< ncnnn >]',
            			perpage: pagingLimit,
            			onSelect: function (page) {
            				limit=pagingLimit;
            				offset=(page-1)*limit;
            				if(!firstLoadPages){
            					initdata(false);
            				}
            				firstLoadPages=false;
            		    	return false;
            			},
            			onFormat: function (type) {
            				switch (type) {
            				case 'block': // n and c
            					if (!this.active)
            						return '';
            					else if (this.value != this.page)
            						return '<li><a href="#">' + this.value + '</a></li>';
            					return '<li class="active"><a href="#">' + this.value + '</a></li>';
            				case 'next': // >
            					return '<li><a href="#">&rsaquo;</a><li>';
            				case 'prev': // <
            						return '<li><a href="#">&lsaquo;</a><li>';
            				case 'first': // [
            						return '<li><a href="#">&laquo;</a><li>';
            				case 'last': // ]
            						return '<li><a href="#">&raquo;</a></li>';
            				}
            			}
            		});
        	}
        }
	});
}
Date.prototype.Format = function(fmt)
{
  var o = {
    "M+" : this.getMonth()+1,                 //月份
    "d+" : this.getDate(),                    //日
    "h+" : this.getHours(),                   //小时
    "m+" : this.getMinutes(),                 //分
    "s+" : this.getSeconds(),                 //秒
    "q+" : Math.floor((this.getMonth()+3)/3), //季度
    "S"  : this.getMilliseconds()             //毫秒
  };
  if(/(y+)/.test(fmt))
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  for(var k in o)
    if(new RegExp("("+ k +")").test(fmt))
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt;
}
